'use strict';
const ms = require('ms');

module.exports = app => {
  return class LoginController extends app.Controller {
    // 登录页
    async loginPage() {
      const ctx = this.ctx;
      if (ctx.session.userInfo) {
        ctx.redirect('/admin');
      }
      ctx.locals = {
        page_title: '登录',
        site: app.config.site,
        bodyClass: 'signin',
        errMsg: ctx.session.errMsg
      };
      if (ctx.session.errMsg)
        ctx.session.errMsg = null;
      await ctx.render('admin/login.html');
    }

    // 登录
    async login() {
      const ctx = this.ctx;
      if (ctx.session.userInfo) {
        ctx.redirect('/admin');
      }
      const body = ctx.request.body;
      if (body.remember === 'true') {
        ctx.session.maxAge = ms('30d');
      }
      const post = await ctx.service.login.post(body);
      if (post) {
        if (post.user_id) {
          ctx.session.userInfo = post;
          ctx.redirect('/admin');
        } else {
          ctx.locals = {
            page_title: '登录',
            site: app.config.site,
            bodyClass: 'signin',
            errMsg: post.message
          }
          await ctx.render('admin/login.html');
        }
      }

    }

    // 登出
    async logout() {
      const ctx = this.ctx;
      ctx.session.userInfo = null;
      ctx.redirect('/admin/login');
    }
  };
};
